import React, { useState, useMemo } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import './table.scss';

interface Column<T> {
  title: string;
  dataIndex: keyof T;
  key: string;
  render?: (text: any, record: T, index: number) => React.ReactNode;
  sorter?: (a: T, b: T) => number;
  width?: number | string;
  align?: 'left' | 'center' | 'right';
}

interface TableProps<T> {
  columns: Column<T>[];
  dataSource: T[];
  rowKey: string | ((record: T) => string);
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    onChange: (page: number) => void;
  };
  loading?: boolean;
  scroll?: {
    x?: number | string | boolean;
    y?: number | string | boolean;
  };
}

function Table<T extends Record<string, any>>({
  columns,
  dataSource: rawDataSource,
  rowKey,
  pagination,
  loading = false,
  scroll,
}: TableProps<T>) {
  const [sortOrder, setSortOrder] = useState<{ key: string; order: 'ascend' | 'descend' } | null>(null);

  // 处理排序
  const dataSource = useMemo(() => {
    if (!sortOrder) return rawDataSource;

    const column = columns.find(col => col.key === sortOrder.key);
    if (!column?.sorter) return rawDataSource;

    return [...rawDataSource].sort((a, b) => {
      if (column.sorter) {
        const result = column.sorter(a, b);
        return sortOrder.order === 'ascend' ? result : -result;
      }
      return 0; // 默认不排序
    });
  }, [rawDataSource, sortOrder, columns]);

  // 处理分页
  const paginatedData = useMemo(() => {
    if (!pagination) return dataSource;

    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    return dataSource.slice(start, end);
  }, [dataSource, pagination]);

  // 计算总宽度（用于横向滚动）
  const tableWidth = useMemo(() => {
    if (scroll?.x === true) return 'auto';
    if (typeof scroll?.x === 'number') return `${scroll.x}px`;
    if (typeof scroll?.x === 'string') return scroll.x;

    // 自动计算宽度
    let totalWidth = 0;
    columns.forEach(col => {
      if (col.width) {
        if (typeof col.width === 'number') totalWidth += col.width;
        else if (col.width.endsWith('px')) totalWidth += parseInt(col.width);
      }
    });
    return totalWidth > 0 ? `${totalWidth}px` : 'auto';
  }, [columns, scroll]);

  const getRowKey = (record: T, index: number) => {
    if (typeof rowKey === 'string') {
      return record[rowKey] as string;
    }
    return rowKey?.(record) || `${index}`; // 添加回退方案
  };

  const handleSort = (column: Column<T>) => {
    if (!column.sorter) return;

    let order: 'ascend' | 'descend' = 'ascend';
    if (sortOrder?.key === column.key) {
      order = sortOrder.order === 'ascend' ? 'descend' : 'ascend';
    }

    setSortOrder({ key: column.key, order });
  };

  // 渲染前检查必要属性是否存在
  if (!columns || !Array.isArray(columns)) {
    console.error('Table columns prop is required and must be an array');
    return <View>Table configuration error</View>;
  }

  return (
    <View className='table-container'>
      {loading && <View className='table-loading'>加载中...</View>}

      <ScrollView
        scrollX={!!scroll?.x}
        scrollY={!!scroll?.y}
        className='table-scroll-view'
        style={
          scroll?.y
            ? { maxHeight: typeof scroll.y === 'boolean' ? '100%' : scroll.y }
            : undefined}
      >
        <View className='table' style={{ width: tableWidth }}>
          {/* 表头 */}
          <View className='table-header'>
            {columns.map((column) => (
              <View
                key={column.key}
                className='table-header-cell'
                style={{
                  width: column.width,
                  textAlign: column.align || 'left',
                  cursor: column.sorter ? 'pointer' : 'default',
                }}
                onClick={() => handleSort(column)}
              >
                <Text>{column.title}</Text>
                {column.sorter && (
                  <View className='sort-icon'>
                    {sortOrder?.key === column.key && (
                      <Text>{sortOrder.order === 'ascend' ? '↑' : '↓'}</Text>
                    )}
                  </View>
                )}
              </View>
            ))}
          </View>

          {/* 表格内容 */}
          <View className='table-body'>
            {paginatedData.map((record, rowIndex) => (
              <View key={getRowKey(record, rowIndex)} className='table-row'>
                {columns.map((column) => (
                  <View
                    key={column.key}
                    className='table-cell'
                    style={{
                      width: column.width,
                      textAlign: column.align || 'left',
                    }}
                  >
                    {column.render
                      ? column.render(record[column.dataIndex], record, rowIndex)
                      : record[column.dataIndex]}
                  </View>
                ))}
              </View>
            ))}
          </View>
        </View>
      </ScrollView>

      {/* 分页 */}
      {
        pagination && (
          <View className='table-pagination'>
            <View className='pagination-info'>
              共 {pagination.total} 条数据，每页 {pagination.pageSize} 条
            </View>
            <View className='pagination-controls'>
              <View
                className={`pagination-item ${pagination.current === 1 ? 'disabled' : ''}`}
                onClick={() => pagination.current > 1 && pagination.onChange(pagination.current - 1)}
              >
                上一页
              </View>
              {[...Array(Math.ceil(pagination.total / pagination.pageSize))].map((_, index) => (
                <View
                  key={index}
                  className={`pagination-item ${pagination.current === index + 1 ? 'active' : ''}`}
                  onClick={() => pagination.onChange(index + 1)}
                >
                  {index + 1}
                </View>
              ))}
              <View
                className={`pagination-item ${pagination.current === Math.ceil(pagination.total / pagination.pageSize)
                  ? 'disabled'
                  : ''
                  }`}
                onClick={() =>
                  pagination.current < Math.ceil(pagination.total / pagination.pageSize) &&
                  pagination.onChange(pagination.current + 1)
                }
              >
                下一页
              </View>
            </View>
          </View>
        )
      }
    </View >
  );
}

export default Table;